// http.js
import baseUrl from './baseUrl.js';

const http = {
	// 通用请求方法封装
	request(config) {
		// 请求前的拦截处理
		config = beforeRequest(config);

		// 拼接 URL
		config.url = baseUrl + config.url;

		return new Promise((resolve, reject) => {
			uni.request({
				url: config.url,
				method: config.method || 'GET',
				data: config.data || {},
				header: config.header || {},
				timeout: config.timeout || 10000,
				success: (res) => {
					// 响应拦截处理
					const response = beforeResponse(res);
					if (response.success) {
						resolve(response.data);
					} else {
						reject(response.error || '请求失败');
					}
				},
				fail: (err) => {
					errorHandle(err);
					reject(err);
				},
			});
		});
	},

	// GET 请求封装
	get(url, data = {}, auth = false, loading = true) {
		return this.request({
			url,
			data: {
				...data,
				login_type: 1,
			},
			auth,
			method: 'GET',
			loading,
		});
	},

	// POST 请求封装
	post(url, data = {}, auth = false, loading = true) {
		return this.request({
			url,
			data,
			auth,
			method: 'POST',
			loading,
		});
	},

	// PUT 请求封装
	put(url, data = {}, auth = false, loading = true) {
		return this.request({
			url,
			data,
			auth,
			method: 'PUT',
			loading,
		});
	},

	// DELETE 请求封装
	delete(url, data = {}, auth = false, loading = true) {
		return this.request({
			url,
			data,
			auth,
			method: 'DELETE',
			loading,
		});
	},
};

// 请求拦截器
const beforeRequest = (config) => {

	if (!config.loading) {
		uni.showLoading({
			title: '加载中...',
			mask: true,
		});
	}
	config.header = config.header || {};
	if (config.auth) {
		const token = uni.getStorageSync('token');
		if (token) {
			config.header['Authorization'] = `bearer ${token}`;
		} else {
			uni.reLaunch({
				url: '/pages/login/login',
			});
			return false;
		}
	}
	return config;
};

// 响应拦截器
const beforeResponse = (response) => {
	uni.hideLoading();
	if (response.statusCode === 200) {
		return {
			success: true,
			data: response.data,
		};
	} else if (response.statusCode === 401) {
		uni.showToast({
			title: '未授权，请登录',
			icon: 'none',
		});
		// 需要移除的键数组
		const keysToRemove = ['expirationTime', 'token', 'Bearer', 'userInfo'];

		// 移除每个键
		keysToRemove.forEach(key => {
			console.log(key)
			uni.removeStorage({
				key: key,
				success: function() {
					console.log(`${key} was removed successfully.`);
				},
				fail: function() {
					console.log(`Failed to remove ${key}.`);
				}
			});
		});
		uni.reLaunch({
			url: '/pages/login/login',
		});

		return {
			success: false,
			error: '未授权',
		};
	} else {
		uni.showToast({
			title: response.data.msg || '请求失败',
			icon: 'none',
		});
		return {
			success: false,
			error: response.data.msg || '请求失败',
		};
	}
};

// 错误处理
const errorHandle = (err) => {
	uni.hideLoading();
	uni.showToast({
		title: '网络错误，请稍后再试',
		icon: 'none',
	});
	console.error('请求失败', err);
};

export default http;